<template>
  <div>
    <!-- 吸顶距离 -->
    <van-sticky>
      <van-nav-bar
        left-text="返回"
        left-arrow
        @click-right="onClickRight"
      >
        <template #left>
          <img
            src="@/assets/images/logo.png"
            class="logo"
          >
        </template>
        <template #right>
          <van-icon
            name="search"
            size="18"
          />
        </template>
      </van-nav-bar>
      <!-- 滚动轮播 频道-->

      <van-tabs
        offset-top
        animated
        @click='onClick'
        v-model="id"
      >
        <van-tab
          v-for="item in list"
          :title="item.name"
          :key="item.id"
          :name="item.id"
        >

        </van-tab>
        <!-- 加号增加类别 -->
        <template #nav-right>

          <van-icon
            name="add-o"
            class="add"
            size="20"
            @click="add"
          />
          <!-- 弹出层 增加类别 -->
          <van-popup v-model="show">
            <!-- 组件 -->
            <channerl
              @close='show=!show'
              @add='addr'
              :list='list'
              @delmit='delmit'
              @entfn='entfn'
            >
            </channerl>
          </van-popup>

        </template>
      </van-tabs>
    </van-sticky>
    <!-- 刷新 -->
    <template>
      <!-- 下拉刷新 -->
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :immediate-check="false"
        @load="onLoad"
      >
        <!-- 上拉刷新 -->
        <van-pull-refresh
          v-model="isLoading"
          @refresh="onRefresh"
        >
          <!-- 列表详情 -->
          <articles
            v-for="(item,index) in lister"
            :key="index"
            :arr='item'
            :i='index'
            :arry="lister"
          >
          </articles>
        </van-pull-refresh>
      </van-list>
    </template>
  </div>
</template>

<script>
// 导入 axios
import articles from './components/articles.vue'
import { getUserSelectionInformation } from '@/api/home.js'
// 导入增加频道的接口
import { increasingChannel } from '@/api/channel.js'
import { getarticles } from '@/api/articles.js'
import { Toast } from 'vant'
import channerl from './components/channeManager.vue'

let cacheObj = {}   //缓存频道数据

// 导入局部组件必须在scrip里面导入,在App里面导入
export default {
  // 组件名称
  name: '',
  // 组件参数 接收来自父组件的数据
  props: {},
  // 接收局部注册的组件
  components: {
    articles,
    channerl
  },
  // 组件数据
  data () {
    return {
      cacheObj,
      show: false,
      // 轮动数据 频道列表
      list: [],
      id: 0,//频道id
      loading: false,
      finished: false,
      // 详情列表
      lister: [],
      isLoading: false,
      pre_timestamp: ''
    }
  },
  methods: {


    // 跳转频道
    entfn (id) {
      this.id = id
      this.show = false
    },



    // 删除频道
    delmit (id) {
      // console.log(id);
      this.list = this.list.filter(item => item.id !== id)
      // const channels =this.list.reduce(())
      // increasingChannel([id])
    },
    //增加频道
    addr (item) {
      this.list.push(item)
    },

    add () {
      this.show = !this.show
    },
    onClickRight () {
      this.$router.push({
        path: '/search'
      })
    },
    // id放起来  轮播频道id
    async onClick (name, title) {
      console.log(name)
      try {

        // 判断本地有没有数据 有就直接return
        if (cacheObj[name] && cacheObj[name].lister) {
          this.lister = cacheObj[name].lister
          this.pre_timestamp = cacheObj[name].timestamp
          // console.log(cacheObj[this.id].lister);
          return
        }


        // console.log(name);
        const req = await getarticles({
          channel_id: this.id,
          timestamp: this.pre_timestamp
        })
        this.pre_timestamp = req.data.data.pre_timestamp
        this.lister = req.data.data.results

        //缓存频道数据列表
        if (cacheObj[this.id] === undefined) {
          cacheObj[this.id] = {}
        }

        cacheObj[this.id].lister = this.lister
        cacheObj[this.id].timestamp = this.pre_timestamp


      } catch (error) {

      }
    },
    // 下拉刷新
    onRefresh () {
      setTimeout(async () => {
        Toast('刷新成功')
        this.isLoading = false
        try {
          const req = await getarticles({
            channel_id: this.id,
            timestamp: this.pre_timestamp
          })
          this.lister = req.data.data.results
          // 获取上一次时间戳 存起来
          this.pre_timestamp = req.data.data.pre_timestamp
          // console.log(req.data.data.results[0].cover.images);
        } catch (error) {

        }
      }, 1000)
    },
    // 上拉
    async onLoad () {
      console.log('onLoad')
      // 异步更新数据
      this.loading = true
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      try {
        const req = await getarticles({
          channel_id: this.id,
          timestamp: this.pre_timestamp
        })
        this.lister.push(...req.data.data.results)
        // 获取上一次时间戳 存起来
        this.pre_timestamp = req.data.data.pre_timestamp

        this.loading = false

        // 数据全部加载完成
        if (req.data.data.results.length == 0) {
          this.finished = true
        }
      } catch (error) {

      }
    }

  },
  beforeRouteLeave (to, from, next) {
    // 记录滚动的位置  传递给路由里面的meta
    from.meta.scrollY = window.scrollY
    // console.log('home', window.scrollY);
    next()
  },
  async activated () {

    //  try cath 放可能出错的代码
    try {
      // 用的api下面的接口

      const resp = await getUserSelectionInformation()
      this.list = resp.data.data.channels

      // console.log(resp.data.data.channels);
      // 列表代码
      const req = await getarticles({
        channel_id: this.id,
        timestamp: this.pre_timestamp
      })
      this.lister = [...this.lister, ...req.data.data.results]
      //缓存频道数据列表
      if (cacheObj[this.id] === undefined) {
        cacheObj[this.id] = {}
      }
      console.log(this.id)
      cacheObj[this.id].lister = this.lister
      cacheObj[this.id].timestamp = req.data.data.pre_timestamp
      //滚动打上次查看的位置
      this.$nextTick(() => {
        //当页面回来的时候 滚动到路由记录的位置
        window.scrollTo(0, this.$route.meta.scrollY)
        // console.log(this.$route.meta.scrollY);
      })

    } catch (error) {
      // try中的代码一旦出错,立马会被cath捕获到
      // console.log(error);
    } finally {

    }
  },
  watch: {
    // 侦听数组
    list (newval) {
      // console.log(newval);
      // 需要对new进行改造
      const channels = newval.reduce((sum, obj, index) => {
        const item = {
          id: obj.id,
          seq: index + 1
        }
        if (item.id !== 0) {
          sum.push(item)
        }
        return sum
      }, [])
      increasingChannel(channels)
    }
  },

}
</script>
<style lang='less' scoped>
.add {
  line-height: 43px;
  position: fixed;
  right: 2px;
  background: #fff;
}
.logo {
  width: 100px;
  height: 30px;
}
.van-popup {
  width: 100%;
  height: 100%;
  // background: goldenrod;
}
</style>
